package org.datavis.event;
import org.datavis.chart.Chart;
import org.datavis.renderer.ChartRenderer;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

public class ChartTouchListener implements View.OnTouchListener{


	private ChartRenderer chartRenderer;
    private Paint   mPaint;
    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;
    
    public ChartTouchListener(ChartRenderer chartRenderer, Chart chart)
    {
    	this.chartRenderer = chartRenderer;
    	mPaint = new Paint();
    	mPaint.setColor(0x44111177);
    }
    
	public boolean onTouch(View v, MotionEvent event) {
		
		float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                chartRenderer.invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                chartRenderer.evaluateTouchEvent();
                break;
        }
        return true;
	}

    private void touch_start(float x, float y) {
        mY = 0;
    	mX = x;        
    }
    
    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE)
        {
            mY = x;
            chartRenderer.setSelection((int)(mX),(int)(mY));
        }           
    }
    
    private void touch_up() {
    	chartRenderer.setSelection((int)(mX),(int)(mY));
    	mX = 0;
		mY = 0;
    }
}
